package cn.turboinfo.fuyang.api.gateway.admin.framework.http.interceptor

import cn.turboinfo.fuyang.api.entity.admin.exception.user.SysUserNotLoginException
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.context.AdminRequestContextHolder
import cn.turboinfo.fuyang.api.gateway.web.framework.http.annotation.SessionScope
import cn.turboinfo.fuyang.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter
import mu.KotlinLogging
import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestParameterTypeBinding
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import kotlin.jvm.optionals.getOrNull

@Component
class AdminSessionScopeInterceptor(
    private val autoMappingRequestParameterTypeBinding: AutoMappingRequestParameterTypeBinding,
) : BaseHandlerInterceptorAdapter() {

    private val logger = KotlinLogging.logger {}

    @OptIn(ExperimentalStdlibApi::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (handler is HandlerMethod) {
            val annotation = getAnnotation(
                handler,
                SessionScope::class.java,
                true
            ).getOrNull()
                ?: autoMappingRequestParameterTypeBinding.getAnnotation(
                    handler.method,
                    SessionScope::class.java,
                    true
                )
                ?: return true

            val throwException = annotation.throwException

            val requestContext = AdminRequestContextHolder.current()

            if (!requestContext.isLogin) {
                if (throwException) {
                    throw SysUserNotLoginException("系统用户未登录")
                }
            }
        }

        return true
    }
}